package org.txazo.music.commons.mp3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class SongerImageSearcher {

	public static final String KOGOU_ALBUM_SEARCH_URL = "http://music.baidu.com/search?key=";

	public static String getURL(String word) {
		StringBuilder sb = new StringBuilder(150);
		sb.append(KOGOU_ALBUM_SEARCH_URL);
		sb.append(word);
		return sb.toString();
	}

	public static String getImageURL(String word) {
		String imageURL = null;
		BufferedReader br = null;
		try {
			URL url = new URL(getURL(word));
			br = new BufferedReader(new InputStreamReader(url.openStream()));

			String temp = null;
			boolean flag = true;
			while ((temp = br.readLine()) != null) {
				temp = temp.trim();
				if (temp.startsWith("<div class=\"target-artist clearfix\"")) {
					flag = true;
				}
				if (flag) {
					if (temp.startsWith("<img src=\"")) {
						imageURL = temp.split("\"")[1].trim();
					}
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return imageURL;
	}

	public static void main(String[] args) {
		System.out.println(getImageURL("许嵩"));
		System.out.println(getImageURL("林俊杰"));
		System.out.println(getImageURL("凤凰传奇"));
	}

}
